package com.mycjj.android.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.ProjectDataManage;
import com.mycjj.android.R;
import com.mycjj.android.activity.Score_ConsumeGetGoldActivity;
import com.mycjj.android.activity.Score_GoldConsumeActivity;
import com.mycjj.android.activity.Score_GoldExchangeActivity;
import com.mycjj.android.activity.Score_GoldRecordActivity;
import com.mycjj.android.activity.Score_GuaGuaCardActivity;
import com.mycjj.android.activity.Score_LotteryListActivity;
import com.mycjj.android.activity.Score_MyGiftActivity;
import com.mycjj.android.activity.Score_ShareGetGoldActivity;
import com.mycjj.android.activity.Score_SignRecordActivity;
import com.mycjj.android.bean.BaseBean;
import com.mycjj.android.bean.GetSignsBaseBean;
import com.mycjj.android.bean.LeveLRuleBean;
import com.mycjj.android.bean.GetSignsBaseBean.SignBean;
import com.mycjj.android.bean.LoginMemberBean;
import com.mycjj.android.bean.MemberBean;
import com.mycjj.android.bean.MemberBean.Member;
import com.mycjj.android.bean.SettingBaseBean;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.util.Preferences;
import com.mycjj.android.util.Utils;
//积分
public class IntegralFragment extends BaseFragment implements android.view.View.OnClickListener {

	private ImageView mHeaderLeftButton;
	private ImageView mHeaderRightButton;
	private TextView mHeaderTitleTextView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = (View) inflater.inflate(R.layout.fragment_integral, null);
		init(view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

	}
	
	private TextView mTv_score,mTv_cardnum;
	private View mLl_note_item,mLl_shopping_item,mLl_share_item;
	
	private View mRl_lucky_item,mRl_guaguacard_item,mRl_exchage_item,mRl_shopping_item;
	
	private View mRl_my_gift_item,mRl_ingot_log_item;
	
	private  TextView tv_v1,tv_v2,tv_v3,tv_v4,tv_v5;
	private ImageView iv_note;
	private TextView tv_note;
	private void init(View view) {

		mHeaderLeftButton = (ImageView) view
				.findViewById(R.id.header_left_button);
		mHeaderLeftButton.setVisibility(View.GONE);
		mHeaderRightButton = (ImageView) view.findViewById(R.id.header_right_button);
		mHeaderRightButton.setVisibility(View.INVISIBLE);
		mHeaderRightButton.setBackgroundResource(R.drawable.iv_right_bg);
		mHeaderTitleTextView = (TextView) view
				.findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("积分");
		mHeaderTitleTextView.setTextSize(16.0f);
		mHeaderRightButton.setOnClickListener(this);
		
		tv_v1 = (TextView) view.findViewById(R.id.tv_v1);
		tv_v2 = (TextView) view.findViewById(R.id.tv_v2);
		tv_v3 = (TextView) view.findViewById(R.id.tv_v3);
		tv_v4 = (TextView) view.findViewById(R.id.tv_v4);
		tv_v5 = (TextView) view.findViewById(R.id.tv_v5);
		mTv_score = (TextView)view.findViewById(R.id.tv_score);
		mTv_cardnum = (TextView)view.findViewById(R.id.tv_cardnum);
		
		mLl_note_item = view.findViewById(R.id.ll_note_item);
		mLl_note_item.setOnClickListener(this);
		
		mLl_shopping_item = view.findViewById(R.id.ll_shopping_item);
		mLl_shopping_item.setOnClickListener(this);
		
		mLl_share_item = view.findViewById(R.id.ll_share_item);
		mLl_share_item.setOnClickListener(this);
		
		mRl_lucky_item = view.findViewById(R.id.rl_lucky_item);
		mRl_lucky_item.setOnClickListener(this);
		
		mRl_guaguacard_item = view.findViewById(R.id.rl_guaguacard_item);
		mRl_guaguacard_item.setOnClickListener(this);
		
		mRl_exchage_item = view.findViewById(R.id.rl_exchage_item);
		mRl_exchage_item.setOnClickListener(this);
		
		mRl_shopping_item = view.findViewById(R.id.rl_shopping_item);
		mRl_shopping_item.setOnClickListener(this);
		
		mRl_my_gift_item = view.findViewById(R.id.rl_my_gift_item);
		mRl_my_gift_item.setOnClickListener(this);
		
		mRl_ingot_log_item = view.findViewById(R.id.rl_ingot_log_item);
		mRl_ingot_log_item.setOnClickListener(this);
		
		tv_note = (TextView)view.findViewById(R.id.tv_note);
		iv_note = (ImageView)view.findViewById(R.id.iv_note);
		
		isSign = Preferences.getSharedPreferences(mApp, "isSign", false);
		if(isSign){
			tv_note.setTextColor(getResources().getColor(R.color.red));
			iv_note.setImageResource(R.drawable.btn_note_sel);
		}
		
		initPoints();
		initLevel();
		initSettingData();
	}
	private String member_id;
	private void initPoints(){
		requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
		RequestParams params = new RequestParams();
		params.put("client_id",ProjectHttpRequestInterface.client_id_key);
		params.put("token", Preferences.getSharedPreferences(getActivity(), "user_token", ""));
		requestInterface.requestUserGetAccountDoneHandler("", params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				BaseBean<?> baseBean = dataInstance.getBaseBean();
				if(baseBean != null){
					if(baseBean.getCode() == 200){
						Map<String,String> map = (Map<String,String>)baseBean.getData();
						String total_points_str = map.get("member_total_points");
						String points_str = map.get("member_points");
						member_id = map.get("member_id");
						
						int total_points = 0,points = 0;
						try{
							total_points = Integer.parseInt(total_points_str);
						}catch(Exception e){
							total_points = 0;
							e.printStackTrace();
						}
						try{
							points = Integer.parseInt(points_str);
						}catch(Exception e){
							points = 0;
							e.printStackTrace();
						}
						dataInstance.setPoints(points);
						dataInstance.setTotalPoints(total_points);
						initData();
						Log.e("mark", "baseBean total_points:"+total_points+";points:"+points);
					}else{
						Toast.makeText(getActivity(),
								baseBean.getMsg(),
								Toast.LENGTH_SHORT).show();
					}
				}else{
					Log.e("mark", "baseBean is null!!");
				}
			}
		});
	}
	
	private void initLevel(){
		requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
		RequestParams params = new RequestParams();
		params.put("client_id",ProjectHttpRequestInterface.client_id_key);
		params.put("token", Preferences.getSharedPreferences(getActivity(), "user_token", ""));
		requestInterface.requestUserGetLevelRuleWithDoneHandler("", params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				//TODO 判断等级区间,为tv_v1，tv_v2，tv_v3，tv_v4设置不同的背景
				ObjectMapper mapper = new ObjectMapper();
				try {
					LeveLRuleBean bean = mapper.readValue(content, LeveLRuleBean.class);
					if(null != bean && bean.getData().size() > 0){
						
						Map<String, String[]> map = bean.getData();
						Set<String> setdate = map.keySet();
						
						int score = dataInstance.getTotalPoints();
						Log.i("info", "--ethan==--"+Arrays.toString(bean.getData().get("1"))
								+"--score="+score);
						for (String strKey : setdate) {
							String[] strScore = map.get(strKey);
							if(Integer.parseInt(strScore[0]) <= score &&  score < Integer.parseInt(strScore[1])){
								if("1".equals(strKey)){
									tv_v1.setBackgroundResource(R.drawable.circle_bg);
									tv_v1.setTextColor(getResources().getColor(R.color.white));
									tv_v2.setBackgroundResource(0);
									tv_v2.setTextColor(getResources().getColor(R.color.black));
									tv_v3.setBackgroundResource(0);
									tv_v3.setTextColor(getResources().getColor(R.color.black));
									tv_v4.setBackgroundResource(0);
									tv_v4.setTextColor(getResources().getColor(R.color.black));
									tv_v5.setBackgroundResource(0);
									tv_v5.setTextColor(getResources().getColor(R.color.black));
								}else if ("2".equals(strKey)){
									tv_v1.setBackgroundResource(0);
									tv_v1.setTextColor(getResources().getColor(R.color.black));
									tv_v2.setBackgroundResource(R.drawable.circle_bg);
									tv_v2.setTextColor(getResources().getColor(R.color.white));
									tv_v3.setBackgroundResource(0);
									tv_v3.setTextColor(getResources().getColor(R.color.black));
									tv_v4.setBackgroundResource(0);
									tv_v4.setTextColor(getResources().getColor(R.color.black));
									tv_v5.setBackgroundResource(0);
									tv_v5.setTextColor(getResources().getColor(R.color.black));
								}else if ("3".equals(strKey)){
									tv_v1.setBackgroundResource(0);
									tv_v1.setTextColor(getResources().getColor(R.color.black));
									tv_v2.setBackgroundResource(0);
									tv_v2.setTextColor(getResources().getColor(R.color.black));
									tv_v3.setBackgroundResource(R.drawable.circle_bg);
									tv_v3.setTextColor(getResources().getColor(R.color.white));
									tv_v4.setBackgroundResource(0);
									tv_v4.setTextColor(getResources().getColor(R.color.black));
									tv_v5.setBackgroundResource(0);
									tv_v5.setTextColor(getResources().getColor(R.color.black));
								}else if ("4".equals(strKey)){
									tv_v1.setBackgroundResource(0);
									tv_v1.setTextColor(getResources().getColor(R.color.black));
									tv_v2.setBackgroundResource(0);
									tv_v2.setTextColor(getResources().getColor(R.color.black));
									tv_v3.setBackgroundResource(0);
									tv_v3.setTextColor(getResources().getColor(R.color.black));
									tv_v4.setBackgroundResource(R.drawable.circle_bg);
									tv_v4.setTextColor(getResources().getColor(R.color.white));
									tv_v5.setBackgroundResource(0);
									tv_v5.setTextColor(getResources().getColor(R.color.black));
								}else if ("5".equals(strKey)){
									tv_v1.setBackgroundResource(0);
									tv_v1.setTextColor(getResources().getColor(R.color.black));
									tv_v2.setBackgroundResource(0);
									tv_v2.setTextColor(getResources().getColor(R.color.black));
									tv_v3.setBackgroundResource(0);
									tv_v3.setTextColor(getResources().getColor(R.color.black));
									tv_v4.setBackgroundResource(0);
									tv_v4.setTextColor(getResources().getColor(R.color.black));
									tv_v5.setBackgroundResource(R.drawable.circle_bg);
									tv_v5.setTextColor(getResources().getColor(R.color.white));
								}
								break;
							}
						}
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				
			}
		});
	}
	
	
	SettingBaseBean settingBaseBean;
	private void initSettingData(){
			settingBaseBean = dataInstance.getSettingBaseBean();
			if (settingBaseBean == null) {
				requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
				RequestParams params = new RequestParams();
				params.put("client_id", ProjectHttpRequestInterface.client_id_key);
				String token = Preferences.getSharedPreferences(getActivity(), "user_token",
						"");
				params.put("token", token);
				requestInterface.requestSyceeGetSettingWithDoneHandler("", params,
						new AsyncHttpResponseHandler() {
							@Override
							public void onSuccess(String content) {
								settingBaseBean = dataInstance.getSettingBaseBean();
								if (settingBaseBean != null) {
									if (settingBaseBean.getCode() == 200) {
										String points = "5";
										try{
											points = settingBaseBean.getData().getSingin().getPoints_signin();
										}catch(Exception e){
											points = "5";
										}
										Preferences.setEditor(mApp, "sign_score", points);
										
									} else {
										Toast.makeText(getActivity(),
												 settingBaseBean.getMsg(),
												Toast.LENGTH_SHORT).show();
									}
								} else {
									Log.e("mark", "settingBaseBean is null!!");
								}
							}
						});
			} else {
				String points = "5";
				try{
					points = settingBaseBean.getData().getSingin().getPoints_signin();
				}catch(Exception e){
					points = "5";
				}
				Preferences.setEditor(mApp, "sign_score", points);
			}
	}

	private void initData() {
		LoginMemberBean bean = ProjectDataManage.getInstance().getLoginMemberBean();
		if(bean != null){
			MemberBean memberBean = (MemberBean)bean.getData();
			Member member = memberBean.getMember_arr();
			mTv_cardnum.setText(member.getMember_id());
		}else{
			mTv_cardnum.setText(member_id);
		}
		mTv_score.setText(String.valueOf(dataInstance.getPoints()));
	}
	
	@Override
	public void onResume() {
		super.onResume();
		// 请求数据
		initData();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	private boolean isSign;
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.ll_note_item:
			if(isSign){
				getSignRecord(false);
			}else{
				doSign();
			}
			break;
		case R.id.ll_shopping_item:
			doShopping();//消费换元宝界面
			break;
		case R.id.ll_share_item:{//分享领元宝
			Intent intent = new Intent(getActivity(),Score_ShareGetGoldActivity.class);
			startActivity(intent);
		}
		break;
		case R.id.rl_lucky_item:{//元宝抽奖
			Intent intent = new Intent(getActivity(),Score_LotteryListActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.rl_guaguacard_item:{//刮刮卡
			Intent intent = new Intent(getActivity(),Score_GuaGuaCardActivity.class);
			startActivity(intent);
		}
			break;
			
		case R.id.rl_exchage_item:{//元宝兑换
			Intent intent = new Intent(getActivity(),Score_GoldExchangeActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.rl_shopping_item:{//元宝消费
			Toast.makeText(getActivity(), "前方施工,敬请期待!", Toast.LENGTH_SHORT).show();
//			Intent intent = new Intent(getActivity(),Score_GoldConsumeActivity.class);
//			startActivity(intent);
		}
		break;
		case R.id.rl_my_gift_item:{
			Intent intent = new Intent(getActivity(),Score_MyGiftActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.rl_ingot_log_item:{
			Intent intent = new Intent(getActivity(),Score_GoldRecordActivity.class);
			startActivity(intent);
		}
			break;
		}
	}
	
	private void doShopping(){
		Intent intent = new Intent(getActivity(),Score_ConsumeGetGoldActivity.class);
		startActivity(intent);
	}
	
	private void doSign(){
		Log.d("mark", "doSign method");
		requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		String token = Preferences.getSharedPreferences(getActivity(), "user_token", "");
		params.put("token", token);
		
		requestInterface.requestSyceeDoSignWithDoneHandler("", params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				BaseBean<Map> baseBean = (BaseBean<Map>)dataInstance.getBaseBean();
				if(baseBean != null){
					if(baseBean.getCode() == 200 ){
						Preferences.setEditor(mApp, "isSign", true);
						getSignRecord(true);
					}else if(baseBean.getCode() == 3210){
						Preferences.setEditor(mApp, "isSign", true);
						getSignRecord(false);
					}else{
						Toast.makeText(getActivity(), baseBean.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}else{
					Log.e("mark","baseBean is null!!!");
				}
				
			}
		});
	}
	
	private void getSignRecord(final boolean isSigned){
		Log.d("mark", "getSignRecord method isSigned："+isSigned);
		requestInterface = new ProjectHttpRequestImpl(getActivity(), true);
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		String token = Preferences.getSharedPreferences(getActivity(), "user_token", "");
		params.put("token", token);
		String month = Utils.getFormateDate(new Date(), "yyyy-MM");
		params.put("month", month);
		requestInterface.requestSyceeGetSignsWithDoneHandler("", params, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				Log.e("mark", "GetSigns content:"+content);
				GetSignsBaseBean baseBean = dataInstance.getSignsBaseBean();
				if(baseBean != null){
					if(baseBean.getCode() == 200){
						if(isSigned){
							Toast.makeText(getActivity(), "签到成功!", Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(getActivity(), "您今天已经签到过了!", Toast.LENGTH_SHORT).show();
						}
						tv_note.setTextColor(getResources().getColor(R.color.red));
						iv_note.setImageResource(R.drawable.btn_note_sel);
						jump2SignRecord(baseBean.getData());
					}else{
						Toast.makeText(getActivity(), baseBean.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(getActivity(), "GetSignsBaseBean is null!!", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
	}
	
	private void jump2SignRecord(List<SignBean> data){
		Intent intent = new Intent(getActivity(),Score_SignRecordActivity.class);
		intent.putExtra("data", (ArrayList<SignBean>)data);
		startActivity(intent);
	}

}
